<!-- src/components/DrawerPanel.vue -->
<template>
  <div class="drawer-overlay" :class="{ open: visible }" @click="closeDrawer">
    <div class="drawer-panel" :class="{ open: visible }" @click.stop>
      <div class="drawer-header">
        <h3 class="drawer-title">系统信息面板</h3>
        <div style="display: flex; gap: 8px;">
          <!-- <button class="mode-toggle-btn" @click="toggleMode" :title="locationViewMode === 'realtime' ? '切换到历史数据' : '切换到实时数据'">
            {{ locationViewMode === 'realtime' ? '实时' : '历史' }}
          </button> -->
          <button class="close-btn" @click="closeDrawer">×</button>
        </div>
      </div>

      <div class="drawer-content">
        <!-- 任务信息 -->
        <div class="collapse-item" v-for="order in workOrders" :key="order.id">
          <div class="collapse-header" @click="toggleTaskCollapse(order)">
            <span class="header-text">任务编号{{ order.workNo }}<span class="status-running">({{ order.status === '1' ? '进行中' : '已完成' }})</span></span>
            <span class="arrow" :class="{ rotated: activePanels[order.id] }">▶</span>
          </div>
          <div class="collapse-content" :class="{ open: activePanels[order.id] }">
            
           
            <div class="info-item">
              <label>开始时间:</label>
              <span>{{ order.startTime }}</span>
            </div>
            <div class="info-item">
              <label>车号:</label>
              <span>{{ order.trainNo }}</span>
            </div>
          

            <!-- 人员信息 -->
            <div class="personnel-section">
              <div class="personnel-header-collapse" @click="togglePersonnelCollapse(order)">
                <span class="personnel-title">人员信息</span>
                <span class="arrow" :class="{ rotated: activePanels[order.id + '_personnel'] }">▶</span>
              </div>
              
            <div v-show="activePanels[order.id + '_personnel']" class="search-container">
                <input 
                    v-model="personnelSearch[order.id]" 
                    :placeholder="'搜索人员...'" 
                    class="personnel-search-input"
                    @input="filterPersonnel(order.id)"
                />
                </div>


              <div class="person-list" :class="{ open: activePanels[order.id + '_personnel'] }">
                <div v-if="workOrderUsersLoading[order.id]" class="loading-container">
                  <span class="loading-text">加载中...</span>
                </div>
                <!-- <div v-else v-for="user in (workOrderUsers[order.id] || [])" :key="user.id" class="person-item"> -->
                    <div v-else v-for="user in (filteredWorkOrderUsers[order.id] || workOrderUsers[order.id] || [])" :key="user.id" class="person-item">

                  <div class="person-info">
                    <div class="person-name">
                        <span v-if="user.status === '1'" style="color:#81c784"> {{ user.userName }}- <span style="font-size: 12px;">{{ user.phone || "暂无电话" }}</span></span>
                        <span v-else style="color:#f40"> {{ user.userName }}-<span style="font-size: 12px;">{{ user.phone || "暂无电话" }}</span></span>
                       </div>
                    <div>
                      <!-- <div class="person-status" :class="user.status === '1' ? 'online' : 'offline'">
                        {{ user.status === '1' ? '在线' : '离线' }}
                      </div> -->
                      <button
                        class="action-btn"
                        @click="toggleLocationView(user, order)"
                        :class="{ active: locationViewOpen[user.id + '_' + order.workNo] }"
                      >
                        {{ locationViewOpen[user.id + '_' + order.workNo] ? '关闭位置' : '查看位置' }}
                      </button>
                    </div>
                  </div>
                  <!-- <div class="person-details">
                    <div class="detail-item">
                      <label>员工编号:</label>
                      <span>{{ user.userNo }}</span>
                    </div>
                  </div> -->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getWorkOrderList, getWorkOrderUserByWorkNo, getLocationUserByUserWork } from '@/api/bussiness/bussiness'

export default {
  name: 'DrawerPanel',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    locationViewMode: {
      type: String,
      default: 'realtime'
    }
  },
  data() {
    return {
      activePanels: {},  // 存储所有展开状态 { 任务id: boolean, 任务id_personnel: boolean }
      workOrders: [],    // 任务列表
      workOrderUsers: {}, // 任务人员数据 { 任务id: [人员...] }
      workOrderUsersLoading: {}, // 人员加载状态 { 任务id: boolean }
      locationViewOpen: {}, // 位置查看打开状态 { userId_workNo: boolean }
      locationViewLoading: {}, // 位置查看加载状态 { userId_workNo: boolean }
        currentLocationViewData: null, // 当前正在查看的位置数据
        personnelSearch: {}, // 存储每个任务的搜索关键词 { 任务id: 搜索词 }
      filteredWorkOrderUsers: {} // 存储过滤后的人员数据 { 任务id: [过滤后的人员...] }
    }
  },
  methods: {
    closeDrawer() {
      this.$emit('update:visible', false);
    },
    // 切换位置查看模式
    toggleMode() {
      this.$emit('toggleLocationViewMode');
    },
    // 任务展开/收起：收起时同时关闭人员列表
    toggleTaskCollapse(order) {
      const taskKey = order.id
      this.activePanels[taskKey] = !this.activePanels[taskKey]
      if (!this.activePanels[taskKey]) {
        this.activePanels[order.id + '_personnel'] = false
      }

      this.$emit('updateRightInfo', order)
    },
    // 人员列表展开/收起：展开时请求数据
    togglePersonnelCollapse(order) {
      const key = order.id + '_personnel'
      this.activePanels[key] = !this.activePanels[key]
      if (this.activePanels[key]) {
        this.fetchWorkOrderUser(order)
      }
    },
    // 过滤人员信息
    filterPersonnel(orderId) {
      const searchKeyword = (this.personnelSearch[orderId] || '').toLowerCase().trim();
      const originalUsers = this.workOrderUsers[orderId] || [];
      
      if (!searchKeyword) {
        // 如果没有搜索关键词，则显示所有人员
        this.$set(this.filteredWorkOrderUsers, orderId, originalUsers);
        return;
      }
      
      // 根据用户名或工号进行模糊搜索
      const filtered = originalUsers.filter(user => 
        (user.userName && user.userName.toLowerCase().includes(searchKeyword)) ||
        (user.userNo && user.userNo.toLowerCase().includes(searchKeyword))
      );
      
      this.$set(this.filteredWorkOrderUsers, orderId, filtered);
    },
    
    // 修改 fetchWorkOrderUser 方法，在获取数据后初始化过滤数据
    fetchWorkOrderUser(order) {
      this.$set(this.workOrderUsersLoading, order.id, true)
      getWorkOrderUserByWorkNo(order.workNo).then(response => {
          console.log('getWorkOrderUserByWorkNo 响应数据:', response)
        if (response.code === 200 && response.data) {
          this.$set(this.workOrderUsers, order.id, response.data)
          
          // 初始化过滤后的数据为全部人员
          this.$set(this.filteredWorkOrderUsers, order.id, response.data)

          // 转换人员数据格式，供地图标记使用
          const personnelData = response.data.map(user => ({
            id: user.id,
            userNo: user.userNo,
            workNo: order.workNo,
            name: user.userName,
            longitude: user.longitude ? parseFloat(user.longitude) : null,
            latitude: user.latitude ? parseFloat(user.latitude) : null,
            telephone: user.telephone || '',
            online: user.status === '1' // status === '1' 表示在线
          }))

          // 将转换后的人员数据emit给父组件
          this.$emit('updatePersonnelHistory', personnelData)
          console.log('人员数据已发送给地图:', personnelData)
        }
      }).catch(error => {
        console.error('获取任务人员信息失败:', error)
      }).finally(() => {
        this.$set(this.workOrderUsersLoading, order.id, false)
      })
    },
    // 查看/关闭位置信息
      toggleLocationView (user, order) {
      const key = user.id + '_' + order.workNo
      const newValue = !this.locationViewOpen[key]

      if (newValue) {
        // 打开新的位置查看前，先关闭所有其他已打开的位置
        Object.keys(this.locationViewOpen).forEach(k => {
          if (k !== key && this.locationViewOpen[k]) {
            this.$set(this.locationViewOpen, k, false)
          }
        })

        // 打开当前位置
        this.$set(this.locationViewOpen, key, true)

        // 打印参数
        const params = {
          userNo: user.userNo,
          workNo: order.workNo
        }
        console.log('getLocationUserByUserWork 请求参数:', params)

        // 保存当前位置查看数据
        this.currentLocationViewData = {
          user: user,
          order: order,
          params: params
        }

        this.fetchLocationUserByUserWork(user.id, user.userNo, order.workNo)
      } else {
        // 关闭当前位置
        this.$set(this.locationViewOpen, key, false)

        // 关闭时清空数据
        this.currentLocationViewData = null
        this.$emit('updateLocationView', null)
      }
    },
    // 获取人员位置轨迹
    fetchLocationUserByUserWork(userId, userNo, workNo) {
      const key = userId + '_' + workNo
      this.$set(this.locationViewLoading, key, true)
      getLocationUserByUserWork(userNo, workNo).then(response => {
        console.log('getLocationUserByUserWork 响应数据:', response)
          // 将响应数据添加到当前位置查看数据中
          
        if (this.currentLocationViewData && response.data ) {
          this.currentLocationViewData.response = response
          // 发送完整数据给父组件
          if (response.code === 200) {
            this.$emit('updateLocationView', this.currentLocationViewData)
          }
        }
      }).catch(error => {
        console.error('获取人员位置信息失败:', error)
      }).finally(() => {
        this.$set(this.locationViewLoading, key, false)
      })
    },
    // 初始化：获取任务列表，初始化展开状态
    fetchWorkOrderList() {
      const query = {}
      console.log('getWorkOrderList 请求参数:', query)
      getWorkOrderList(query).then(response => {
        console.log('getWorkOrderList 响应数据:', response)
        if (response.code === 200 && response.rows) {
          this.workOrders = response.rows
          this.workOrders.forEach(order => {
            this.$set(this.activePanels, order.id, false)
            this.$set(this.activePanels, order.id + '_personnel', false)
          })
        }
      }).catch(error => {
        console.error('获取任务信息失败:', error)
      })
    }
  },
  mounted() {
    this.fetchWorkOrderList()
  }
}
</script>

<style scoped>
.drawer-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: 2000;
  opacity: 0;
  visibility: hidden;
  transition: opacity 0.3s ease, visibility 0.3s ease;
  pointer-events: none;
}

.drawer-overlay.open {
  opacity: 1;
  visibility: visible;
  pointer-events: auto;
}

.drawer-panel {
  position: absolute;

  width: 350px;
  height: calc(100% - 40px);
  background: #1a3a6a8a;
  box-shadow: 5px 0 25px rgba(0, 0, 0, 0.5);
  transform: translateX(-100%);
  transition: transform 0.3s ease;
  z-index: 2001;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #4fc3f7;
  border-radius: 10px;
}

.drawer-panel.open {
  transform: translateX(0);
}

.drawer-header {
  padding: 20px;
  background:  #0288d1b3;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(79, 195, 247, 0.3);
  border-radius: 10px 10px 0 0;
}

.drawer-title {
  color: white;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

.mode-toggle-btn {
  padding: 6px 12px;
  background: rgba(2, 119, 189, 0.3);
  color: #4fc3f7;
  border: 1px solid rgba(79, 195, 247, 0.5);
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  font-weight: 600;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.mode-toggle-btn:hover {
  background: rgba(2, 119, 189, 0.5);
  border-color: #4fc3f7;
  box-shadow: 0 0 10px rgba(79, 195, 247, 0.3);
}

.close-btn {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  cursor: pointer;
  font-size: 18px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(90deg);
}

.drawer-content {
  flex: 1;
  overflow-y: auto;

}

.collapse-item {
  margin-bottom: 15px;
  background: rgba(12, 30, 62, 0.7);
  border-radius: 8px;
  border: 1px solid rgba(79, 195, 247, 0.3);
  overflow: hidden;
}

.collapse-header {
  padding: 15px;
  background: rgba(2, 119, 189, 0.3);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: background 0.3s ease;
}

.collapse-header:hover {
  background: rgba(2, 119, 189, 0.5);
}

.header-text {
  color: #4fc3f7;
  font-weight: 600;
  font-size: 16px;
}

.arrow {
  color: #4fc3f7;
  transition: transform 0.3s ease;
}

.arrow.rotated {
  transform: rotate(90deg);
}

.collapse-content {
  max-height: 0;
  overflow: hidden;
  transition: max-height 0.3s ease;
  background: rgba(12, 30, 62, 0.5);
}

.collapse-content.open {
  max-height: 1000px;
}

.info-item {
  padding: 12px 15px;
  display: flex;
  justify-content: space-between;
  border-bottom: 1px solid rgba(79, 195, 247, 0.1);
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  color: #90caf9;
  font-weight: 500;
}

.info-item span {
  color: #e3f2fd;
  font-weight: 600;
}

.status-running {
  color: #4caf50;
  font-weight: 600;
}

.status-normal {
  color: #2196f3;
  font-weight: 600;
}

.person-list {
  padding: 10px 0;
}

.person-item {
  padding: 5px 15px;
  border-bottom: 1px solid rgba(79, 195, 247, 0.1);
}

.person-item:last-child {
  border-bottom: none;
}

.person-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  gap: 10px;
}

.person-name {
  color: #e3f2fd;
  font-weight: 600;
  font-size: 16px;
  flex: 1;
}

.person-info > div:last-child {
  display: flex;
  gap: 8px;
  align-items: center;
}

.person-status {
  padding: 3px 10px;
  border-radius: 10px;
  font-size: 12px;
  font-weight: 600;
}

.person-status.online {
  background: rgba(76, 175, 80, 0.2);
  color: #81c784;
  border: 1px solid rgba(76, 175, 80, 0.5);
}

.person-status.offline {
  background: rgba(158, 158, 158, 0.2);
  color: #bdbdbd;
  border: 1px solid rgba(158, 158, 158, 0.5);
}

.detail-item {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
}

.detail-item label {
  color: #90caf9;
}

.detail-item span {
  color: #bbdefb;
}

.action-btn {
  padding: 4px 10px;
  background: rgba(2, 119, 189, 0.3);
  color: #4fc3f7;
  border: 1px solid rgba(79, 195, 247, 0.5);
  border-radius: 4px;
  cursor: pointer;
  font-size: 11px;
  font-weight: 600;
  transition: all 0.3s ease;
  white-space: nowrap;
}

.action-btn:hover {
  background: rgba(2, 119, 189, 0.5);
  border-color: #4fc3f7;
  box-shadow: 0 0 10px rgba(79, 195, 247, 0.3);
}

.action-btn.active {
  background: rgba(79, 195, 247, 0.3);
  color: white;
  border-color: #4fc3f7;
}

.battery-level {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;
}

.battery-fill {
  height: 8px;
  background: linear-gradient(90deg, #0277bd, #4fc3f7);
  border-radius: 4px;
  flex: 1;
  position: relative;
  overflow: hidden;
}

.battery-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  animation: shine 2s infinite;
}

@keyframes shine {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.battery-text {
  color: #4fc3f7;
  font-weight: 600;
  min-width: 40px;
  text-align: right;
}

.personnel-section {
  margin-top: 15px;

}

.personnel-header-collapse {
  padding: 12px 10px;
  background: rgba(2, 119, 189, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  border-radius: 4px;
  transition: background 0.3s ease;
}

.personnel-header-collapse:hover {
  background: rgba(2, 119, 189, 0.3);
}

.personnel-title {
  color: #4fc3f7;
  font-weight: 600;
  font-size: 14px;
}

.person-list {
  max-height: 0;
  overflow: scroll;
  transition: max-height 0.3s ease;
}

.person-list.open {
  max-height: 1000px;
}

.loading-container {
  padding: 20px;
  text-align: center;
}

.loading-text {
  color: #4fc3f7;
  font-size: 14px;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.loading-text::before {
  content: '';
  width: 12px;
  height: 12px;
  border: 2px solid #4fc3f7;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 0.8s linear infinite;
}
.search-container {
  padding: 10px;
  background: rgba(12, 30, 62, 0.5);
}

.personnel-search-input {
  width: 100%;
  padding: 8px 12px;
  background: rgba(2, 119, 189, 0.3);
  border: 1px solid rgba(79, 195, 247, 0.5);
  border-radius: 4px;
  color: #e3f2fd;
  font-size: 14px;
  box-sizing: border-box;
}

.personnel-search-input:focus {
  outline: none;
  border-color: #4fc3f7;
  box-shadow: 0 0 8px rgba(79, 195, 247, 0.6);
}

.personnel-search-input::placeholder {
  color: #90caf9;
  opacity: 0.7;
}
@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}
</style>
